package com.gewu.pm.ui.fragment.delivery;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.app.AppFragment;
import com.gewu.pm.bean.DeliveryOrderBean;
import com.gewu.pm.other.IntentKey;
import com.gewu.pm.ui.adapter.delivery.DeliveryOrderAdapter;
import com.hjq.base.BaseAdapter;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 配送订单 Fragment
 */
public final class DeliveryOrderFragment extends AppFragment<AppActivity>
        implements BaseAdapter.OnItemClickListener, OnRefreshLoadMoreListener {

    private SmartRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private DeliveryOrderAdapter mAdapter;

    private int mOrderType;  // 订单类型（1-待发货，2-待签收，3-已签收，4-已取消）
    private int mPageNumber = 1;  // 当前页码
    private static final int PAGE_SIZE = 10;  // 每页数量

    private List<DeliveryOrderBean> mAllDataList = new ArrayList<>();  // 全部数据
    private String mSearchKeyword = "";  // 搜索关键词
    private String mDateFilter = "今日";  // 日期筛选

    public static DeliveryOrderFragment newInstance(int orderType) {
        DeliveryOrderFragment fragment = new DeliveryOrderFragment();
        Bundle args = new Bundle();
        args.putInt(IntentKey.TYPE, orderType);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.delivery_order_fragment;
    }

    @Override
    protected void initView() {
        mRefreshLayout = findViewById(R.id.srl_refresh);
        mRecyclerView = findViewById(R.id.rv_list);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new DeliveryOrderAdapter(getContext());
        mAdapter.setOnItemClickListener(this);
        mRecyclerView.setAdapter(mAdapter);

        mRefreshLayout.setOnRefreshLoadMoreListener(this);
    }

    @Override
    protected void initData() {
        if (getArguments() != null) {
            mOrderType = getArguments().getInt(IntentKey.TYPE, 1);
        }
        
        // 创建测试数据
        createTestData();
        
        // 加载第一页数据
        loadData(true);
    }

    /**
     * 创建测试数据（每个状态创建15条测试数据）
     */
    private void createTestData() {
        mAllDataList.clear();
        
        String[] terminalNames = {
            "终端名称展示在这里",
            "落落超市",
            "银泰大厦便利店",
            "西湖区小卖部",
            "滨江商贸中心",
            "下沙大学城超市",
            "萧山区连锁店",
            "余杭区便利店",
            "拱墅区小商铺",
            "上城区零售店",
            "江干区批发部",
            "富阳区商行",
            "临安区超市",
            "桐庐县门店",
            "建德市零售部"
        };
        
        // 如果是全部（type=0），创建所有状态的数据
        if (mOrderType == 0) {
            for (int type = 1; type <= 4; type++) {
                for (int i = 0; i < 15; i++) {
                    String orderId = "6873929009" + String.format("%02d%02d", type, i + 1);
                    String terminalName = terminalNames[i % terminalNames.length];
                    mAllDataList.add(new DeliveryOrderBean(type, orderId, terminalName));
                }
            }
        } else {
            // 单个状态的数据
            for (int i = 0; i < 15; i++) {
                String orderId = "687392900998" + String.format("%02d", i + 1);
                String terminalName = terminalNames[i % terminalNames.length];
                mAllDataList.add(new DeliveryOrderBean(mOrderType, orderId, terminalName));
            }
        }
    }

    /**
     * 加载数据
     */
    private void loadData(boolean isRefresh) {
        if (isRefresh) {
            mPageNumber = 1;
        }
        
        // 根据搜索关键词过滤数据
        List<DeliveryOrderBean> filteredList = filterData();
        
        // 分页获取数据
        int startIndex = (mPageNumber - 1) * PAGE_SIZE;
        int endIndex = Math.min(startIndex + PAGE_SIZE, filteredList.size());
        
        // 创建新的List副本，避免ConcurrentModificationException
        List<DeliveryOrderBean> pageData = new ArrayList<>();
        if (startIndex < filteredList.size()) {
            for (int i = startIndex; i < endIndex; i++) {
                pageData.add(filteredList.get(i));
            }
        }
        
        // 更新列表
        if (isRefresh) {
            mAdapter.setData(pageData);
            mRefreshLayout.finishRefresh();
        } else {
            mAdapter.addData(pageData);
            mRefreshLayout.finishLoadMore();
        }
        
        // 判断是否还有更多数据
        if (endIndex >= filteredList.size()) {
            mRefreshLayout.setNoMoreData(true);
        }
    }

    /**
     * 根据关键词过滤数据
     */
    private List<DeliveryOrderBean> filterData() {
        if (mSearchKeyword.isEmpty()) {
            return mAllDataList;
        }
        
        List<DeliveryOrderBean> result = new ArrayList<>();
        for (DeliveryOrderBean bean : mAllDataList) {
            if (bean.getTerminalName().contains(mSearchKeyword)) {
                result.add(bean);
            }
        }
        return result;
    }

    /**
     * 搜索（从外部调用）
     */
    public void search(String keyword) {
        mSearchKeyword = keyword;
        loadData(true);
    }

    /**
     * 设置日期筛选（从外部调用）
     */
    public void setDateFilter(String dateFilter) {
        mDateFilter = dateFilter;
        loadData(true);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        // 下拉刷新
        loadData(true);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        // 上拉加载更多
        mPageNumber++;
        loadData(false);
    }

    @Override
    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
        DeliveryOrderBean bean = mAdapter.getItem(position);
        // 跳转到详情页，携带订单ID
        //DeliveryOrderDetailActivity.start(getContext(), bean.getOrderId());
    }
}

